package com.hopedove.tempdemo.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.util.Base64
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.resource.gif.GifDrawable
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.hopedove.tempdemo.common.SERVER_URL_HOST
import com.orhanobut.logger.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class BitmapUtil {

    companion object {

        fun fromBase64(base64: String?): Bitmap? {
            return try {
                Base64.decode(base64, Base64.DEFAULT).let {
                    BitmapFactory.decodeByteArray(it, 0, it.size)
                }
            } catch (e: Exception) {
                null
            }
        }
    }
}


val glideGifBitmap: suspend (RequestManager, String) -> Bitmap = ::glideGetGifBitmap

/**
 *  把每个 URL 对应的 Bitmap 收集起来
 */
suspend fun collectMappingBitmaps(
    scope: CoroutineScope,
    glide: RequestManager,
    urls: List<String>,
    requestBitmap: suspend (RequestManager, String) -> Bitmap = glideGifBitmap
): Map<String, Bitmap> {
    // 把每个 url 对应的 bitmap 下载下来
    val channel = Channel<Pair<String, Bitmap>>()

    scope.launch {
        urls.forEach { path ->
            launch {
                val url = "$SERVER_URL_HOST${path}"
                val bmp = requestBitmap(glide, url)
                channel.send(Pair(path, bmp))
            }
        }
    }.invokeOnCompletion { channel.close() }


    val resultMap = mutableMapOf<String, Bitmap>()
    for ((url, bitmap) in channel) {
        resultMap[url] = bitmap
    }
    Logger.d("collect bitmap maps: $resultMap")
    return resultMap
}


suspend fun glideGetGifBitmap(glide: RequestManager, url: String): Bitmap {
    return suspendCoroutine { cons ->
        glide.asGif().load(url)
            .into(object : CustomTarget<GifDrawable>() {
                override fun onResourceReady(
                    resource: GifDrawable,
                    transition: Transition<in GifDrawable>?
                ) {
                    val bmp = resource.firstFrame
                    cons.resume(bmp)
                }

                override fun onLoadCleared(placeholder: Drawable?) = Unit
            })
    }
}

